from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views.decorators.http import require_http_methods


@require_http_methods(['POST', 'GET'])
def handle_login(request):
    # 获取用户提交方法
    if request.method == 'POST':
        username = request.POST.get('user', None)
        password = request.POST.get('pwd', None)
        # hobbies = request.POST.getlist('hobbies', None)
        # citys = request.POST.getlist('city', None)
        obj = request.FILES.get('my_file', None)
        if obj:
            with open(obj.name, mode='wb') as f:
                for i in obj.chunks():
                    f.write(i)

        if username == 'tengfei' and password == '123456':
            # return render(request, 'login.html')
            return redirect('http://www.baidu.com')
        else:
            return render(request, 'login.html', {
                'error_msg': '用户名和密码不匹配'
            })

    elif request.method == 'GET':
        return render(request, 'login.html')


from django.views import View


class Home(View):

    # urls.py中使用该模块的Home类的as_views()方法，该方法会调用Home类中的dispatch方法，如果不存在就调用父类View中的dispatch方法，
    # 两种方法本质都是调用父类的dispatch方法，但前者可以稍作定制，
    # 父类的dispatch方法判断客户端所使用的方法，例如如果是get方法，就调用Home类中的get方法
    def dispatch(self, request, *args, **kwargs):
        print('before')
        result = super().dispatch(request, *args, **kwargs)
        print('after')
        return result

    def get(self, request):
        return HttpResponse('home get')

    def post(self, request):
        return HttpResponse('home post')


def handle_re(request, age):
    print(reverse('detail', args=[18]))
    return HttpResponse(age)


from .models import User


def add_user(request, username, password):
    User.objects.get_or_create(name=username, password=password)
    return HttpResponse(','.join([username, password]))


def get_users(request):
    users = User.objects.all()
    for user in users:
        print(user.id, user.name, user.password)
    return HttpResponse(users)


def delete_user(request, **kwargs):
    user = User.objects.filter(**kwargs).delete()
    return HttpResponse(user)
